import { App } from "vue";
import type { RouteRecordRaw } from "vue-router";
import { createRouter, createWebHashHistory } from "vue-router";
import { store } from "/@ts/store";
import { FilterRouterArr, basicRoutes } from "/@ts/router/routes";
import { isRelogin } from "/@ts/axios";
import NProgress from "nprogress";
import { ElMessage } from "element-plus";
/**
 * 创建路由实例
 */
NProgress.configure({ showSpinner: false });
export const router = createRouter({
  history: createWebHashHistory(),
  routes: basicRoutes as unknown as RouteRecordRaw[],
});
// console.log('router :>> ', router.getRoutes());
/**
 * 路由拦截 LoginState
 */
let filterArr = FilterRouterArr();
const getFilterRouterName = (name: string): boolean => filterArr.includes(name);
router.afterEach((to, from) => {
  NProgress.done();
});
//页面刷新后重新设置权限页面动态路由，防止出现动态路由404问题

router.beforeEach((to, from, next) => {
  NProgress.start();
  store.commit("loginModule/isLogin");
  const isloginPage: boolean = getFilterRouterName(to.name as string);
  let state: any = store.state;
  if (state.loginModule.isLogin) {
    if (to.path === "/login") {
      next({ path: "/" });
      NProgress.done();
    } else {
      if (state.loginModule.roles.length === 0) {
        isRelogin.show = true;
        // 判断当前用户是否已拉取完user_info信息
        store
          .dispatch("loginModule/GetInfo")
          .then(() => {
            isRelogin.show = false;
            store
              .dispatch("permissionsModule/GenerateRoutes")
              .then((accessRoutes) => {
                for (let index = 0; index < accessRoutes.length; index++) {
                  const element = accessRoutes[index];
                  if (element.meta && !Boolean(element.meta.link)) {
                    router.addRoute(element);
                  }
                }
                next({ ...to, replace: true }); // hack方法 确保addRoutes已完成
              });
          })
          .catch((err) => {
            store.dispatch("loginModule/LogOut").then(() => {
              ElMessage.error(err);
              next({ path: "/login" });
            });
          });
      } else {
        next();
      }
    }
  } else {
    // 没有token
    if (isloginPage) {
      // 在免登录白名单，直接进入
      next();
    } else {
      next(`/login?redirect=${to.fullPath}`); // 否则全部重定向到登录页
      NProgress.done();
    }
  }

});
/**
 * 挂载到vue实例函数
 * @param app vue实例
 */
export function setupRouter(app: App<Element>) {
  app.use(router);
}

export default router;
